package com.yonyou.framework.library.widgets.pla;


import android.content.Context;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yonyou.framework.library.R;
import com.yonyou.framework.library.progress.CircularProgressBar;


/**
 * Author:  Tau.Chen
 * Email:   1076559197@qq.com | tauchen1990@gmail.com
 * Date:    2015/4/3.
 * Description:
 */
public class PLALoadMoreListView extends PLAMultiColumnListView implements PLAAbsListView.OnScrollListener {

    private OnScrollListener mOnScrollListener;
    private LayoutInflater mInflater;

    // footer view
    private RelativeLayout mFooterView;
    private TextView mLabLoadMore;
    private CircularProgressBar mProgressBarLoadMore;

    // Listener to process load more items when user reaches the end of the list
    private OnLoadMoreListener mOnLoadMoreListener;

    private OnScrollChangedListener mOnScrollChangedListener;

    // To know if the list is loading more items
    private boolean mIsLoadingMore = false;

    private boolean mCanLoadMore = true;
    private int mCurrentScrollState;

    // current first visible item of this listview
    private int mCurrentfirstVisibleItem = 0;

    // sparseArray, to save SCROLLED DISTANCE for listview
    private SparseArray recordSp = new SparseArray(0);

    public PLALoadMoreListView(Context context) {
        super(context);
        init(context);
    }

    public PLALoadMoreListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PLALoadMoreListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        setSelector(R.drawable.transparent);

        // footer
        mFooterView = (RelativeLayout) mInflater.inflate(R.layout.common_load_more_footer, this, false);
        mLabLoadMore = (TextView) mFooterView.findViewById(R.id.common_load_more_footer_msg);
        mProgressBarLoadMore = (CircularProgressBar) mFooterView.findViewById(R.id.common_load_more_footer_progress);

        addFooterView(mFooterView);

        super.setOnScrollListener(this);
    }

    @Override
    public void onScrollStateChanged(PLAAbsListView view, int scrollState) {
        mCurrentScrollState = scrollState;

        if (mOnScrollListener != null) {
            mOnScrollListener.onScrollStateChanged(view, scrollState);
        }
    }

    @Override
    public void onScroll(PLAAbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        mCurrentfirstVisibleItem = firstVisibleItem;
        View firstView = view.getChildAt(0);
        if (null != firstView) {
            ItemRecod itemRecord = (ItemRecod) recordSp.get(firstVisibleItem);
            if (null == itemRecord) {
                itemRecord = new ItemRecod();
            }
            itemRecord.height = firstView.getHeight();
            itemRecord.top = firstView.getTop();
            recordSp.append(firstVisibleItem, itemRecord);

            if(mOnScrollChangedListener != null) {
                mOnScrollChangedListener.onScrolled(getScrolledDistance());
            }

        }

        if (mOnScrollListener != null) {
            mOnScrollListener.onScroll(view, firstVisibleItem,
                    visibleItemCount, totalItemCount);
        }

        if (mOnLoadMoreListener != null) {

            if (visibleItemCount == totalItemCount) {
                mProgressBarLoadMore.setVisibility(GONE);
                mLabLoadMore.setVisibility(GONE);
                return;
            }


            boolean loadMore = firstVisibleItem + visibleItemCount >= totalItemCount;

            if (!mIsLoadingMore && loadMore
                    && mCurrentScrollState != SCROLL_STATE_IDLE) {
                if (!mCanLoadMore) {
                    mLabLoadMore.setVisibility(VISIBLE);
                    return;
                }
                mProgressBarLoadMore.setVisibility(VISIBLE);
                mLabLoadMore.setVisibility(GONE);
                mIsLoadingMore = true;
                onLoadMore();
            }


        }
    }

    public int getScrolledDistance() {
        int height = 0;
        for (int i = 0; i < mCurrentfirstVisibleItem; i++) {
            ItemRecod itemRecod = (ItemRecod) recordSp.get(i);
            height += itemRecod.height;
        }
        ItemRecod itemRecod = (ItemRecod) recordSp.get(mCurrentfirstVisibleItem);
        if (null == itemRecod) {
            itemRecod = new ItemRecod();
        }
        return height - itemRecod.top;
    }


    class ItemRecod {
        int height = 0;
        int top = 0;
    }

    /**
     * Set the listener that will receive notifications every time the list
     * scrolls.
     *
     * @param listener The scroll listener.
     */
    @Override
    public void setOnScrollListener(OnScrollListener listener) {
        mOnScrollListener = listener;
    }

    /**
     * Register a callback to be invoked when this list reaches the end (last
     * item be visible)
     *
     * @param onLoadMoreListener The callback to run.
     */
    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        mOnLoadMoreListener = onLoadMoreListener;
    }

    public void setCanLoadMore(boolean canLoadMore) {
        mCanLoadMore = canLoadMore;
        mLabLoadMore.setVisibility(GONE);
    }

    public void onLoadMore() {
        if (mOnLoadMoreListener != null) {
            mOnLoadMoreListener.onLoadMore();
        }
    }

    /**
     * Notify the loading more operation has finished
     */
    public void onLoadMoreComplete() {
        mIsLoadingMore = false;
        mProgressBarLoadMore.setVisibility(GONE);
    }

    /**
     * Interface definition for a callback to be invoked when list reaches the
     * last item (the user load more items in the list)
     */
    public interface OnLoadMoreListener {
        /**
         * Called when the list reaches the last item (the last item is visible
         * to the user)
         */
        public void onLoadMore();
    }

    /**
     * return current scrolled distance for user
     */
    public interface OnScrollChangedListener {

        /**
         * Called when listview scrolled
         * @param scrollY current distance of the listview scrolled
         */
        void onScrolled(int scrollY);

    }

    public void setOnScrollChangedListener(OnScrollChangedListener l){
        this.mOnScrollChangedListener = l;
    }


}
